<template>
<div>
    <a-card :bordered="false" title="结算基础信息" style="margin-bottom: 10px;">
        <detail-list :col="2">
            <detail-list-item term="结算批次编号">{{detail.settleBatchCode}}</detail-list-item>
            <detail-list-item term="任务名称">{{detail.taskName}}</detail-list-item>
            <detail-list-item term="结算批次名称">{{detail.settleBatchName}}</detail-list-item>
            <detail-list-item term="任务编号">{{detail.taskId}}</detail-list-item>
            <detail-list-item term="结算方式">{{detail.serviceFeeSettleMode === 1 ? '线上':'线下'}}</detail-list-item>
            <detail-list-item term="任务类型">{{detail.type === 1 ? '线上':'线下'}}</detail-list-item>
            <template v-if="userInfo.type === 3">
                <detail-list-item term="关联园区服务商">{{detail.parkName}}</detail-list-item>
            </template>
             <template v-if="userInfo.type === 2">
                <detail-list-item term="关联企业名称">{{detail.enterpriseName}}</detail-list-item>
            </template>
            <detail-list-item term="支付通道">{{detail.payChannel === 1 ? '招商银行':detail.payChannel === 3 ? '支付宝到卡':'支付宝到户'}}</detail-list-item>
            <detail-list-item term="结算状态">
                <span>{{detail.settleStatus | filter_state}}</span>
            </detail-list-item>
        </detail-list>
    </a-card>
    <a-card title="结算统计" style="margin-bottom: 10px;">
        <div style="display: flex;">
            <div id="projectPirceLine" style="height: 240px;flex: 1;"></div>
            <div id="projectNumLine" style="height: 240px;flex: 1;"></div>
        </div>
    </a-card>
    <a-card title="结算人员明细">
        <template slot="extra">
            <a-button type="primary" v-action:settleUploadInteractionBtn @click="$refs.createTaskDeliver.add(true,3)" icon="solution">批量上传交付物</a-button>
            <a-button type="primary" v-action:humanResourcesNodeliverCode class="ant-btn-info" @click="$store.dispatch('allImportNoDeliverables',{settleBatchCode:detail.settleBatchCode})" icon="usergroup-add">导出无交付物用户</a-button>
            <a-button type="primary" v-action:settleExportUserBtn class="ant-btn-warning" @click="$store.dispatch('allImportSttleUser',{settleBatchCode:detail.settleBatchCode,all:1})" icon="usergroup-add">导出所有名单</a-button>
            <a-button type="danger" v-action:settleExportFailUserBtn @click="$store.dispatch('allImportSttleUser',{settleBatchCode:detail.settleBatchCode,all:2})" icon="usergroup-add">导出失败名单</a-button>
            <a-button type="primary" v-action:settleDownlocalSingleBillBtn @click="$store.dispatch('allPreviewLocalReceipt',detail.settleBatchCode)" icon="file-pdf">申请本地回执单</a-button>
            <a-button type="primary" v-action:settleBatchDownBillBtn @click="$store.dispatch('allSeaCmbReceipt',detail.settleBatchCode)" icon="file-pdf">批量下载回执单</a-button>
        </template>
        <form-create v-model="params.fApi" :rule="params.rule" :option="params.option" @btn-search-click="getSettleUserList(true)" @btn-reset-click="reset" @btn-back-click="close"/>
        <a-table 
        :columns="table.columns" 
        :pagination="table.pagination" 
        @change="handleTableChange"
        rowKey="id" 
        :data-source="table.loadData" 
        :scroll="{ x: 2200 }">
            <span slot="action" slot-scope="text, record">
                <a v-action:settleQueryInteractionBtn @click="$refs.createTaskDeliver.add(record,2)">交付物查看</a>
                <a-divider type="vertical" v-action:settleEditBtn/>
                <a v-if="!record.editable" v-action:settleEditBtn @click="editAmount(record.id)">备注编辑</a>
                <template v-if="record.editable">
                  <a v-if="record.editable" @click="saveAmount(record)">保存</a>
                  <a-divider type="vertical" />
                  <a v-if="record.editable" @click="getSettleUserList(false)">取消</a>
                </template>
                <a-divider type="vertical" v-action:settlePreviewReceipt/>
               <a v-action:settlePreviewReceipt @click="$store.dispatch('allisReceipt',record.detailId)">预览回执单</a>
            </span>
            <span slot="bankCard" slot-scope="text, record">
                 <a-popover title="银行卡号/支付宝" trigger="hover">
                    <template #content>
                    <p style="margin: 0;">{{record.bankCard}}</p>
                    </template>
                    <a-button style="padding: 0;color:#000" type="link">{{record.bankCard | filterMore(6)}}</a-button>
                </a-popover>
            </span>
            <span slot="remark" slot-scope="text, record">
                <a-input
                  v-if="record.editable" 
                  style="width: 200px;"
                  :value="text"
                  type="textarea"
                  @change="e => handleChange(e.target.value, record.id, 'remark')"
                  />
                <template v-else>
                    <a-popover title="备注信息" trigger="hover">
                    <template #content>
                    <p style="margin: 0;">{{record.remark}}</p>
                    </template>
                    <a-button style="padding: 0;color:#000" type="link">{{record.remark | filterMore(4)}}</a-button>
                </a-popover>
                </template>
            </span>
            <span slot="settleStatus" slot-scope="text, record">
                <a-tag color="orange" v-if="text===1">待服务商审核</a-tag>
                <a-tag color="blue" v-if="text===2">结算申请中</a-tag>
                <a-tag color="green" v-if="text===3">结算成功</a-tag>
                <a-tag color="pink" v-if="text===4">部分结算成功</a-tag>
                <a-tag color="red" v-if="text===5">结算失败</a-tag>
                <a-tag color="purple" v-if="text===6">已驳回</a-tag>
                <a-tag color="cyan" v-if="text===7">银行发放中</a-tag>
            </span>
            <span slot="idCard" slot-scope="text, record">
                 <a-popover title="身份证号" trigger="hover">
                    <template #content>
                    <p style="margin: 0;">{{record.idCard}}</p>
                    </template>
                    <a-button style="padding: 0;color:#000" type="link">{{record.idCard | filterMore(7)}}</a-button>
                </a-popover>
            </span>
            <span slot="settleFailReason" slot-scope="text, record">
                 <a-popover title="结算失败原因" trigger="hover">
                    <template #content>
                    <p style="margin: 0;">{{record.settleFailReason}}</p>
                    </template>
                    <a-button style="padding: 0;color:#000" type="link">{{record.settleFailReason | filterMore(26)}}</a-button>
                </a-popover>
            </span>
        </a-table>
    </a-card>

    <task-deliver ref="createTaskDeliver" @on-ok="getSettleUserList(true)"/>

</div>

</template>
<script>
import { mapGetters,mapActions } from 'vuex'
import store from '@/store'
import DetailList from '@/components/tools/DetailList'
const DetailListItem = DetailList.Item
import 
  TaskDeliver
from '@/views/application/modules/task_deliver'
import 
  TaskInteraction
from '@/views/application/task/task_interaction'
import {
    PARAMS_SETTLE_USER,
    COLUMNS_TSTTLE_USER,
    OPTION_INLINE,
    options
} from './form'
import { 
    allOnlineTaskDetail
} from '@/api/manage/task'
import { 
    allSettlementDetail,
    allGetTaskDeliverables,
    allSttleDeliveryEdit,
    allGetSettleDetail
} from '@/api/manage/sttle'
import { 
  previewFile
} from '@/utils/util'
import {SETTLE_BILL_DATA} from '@/config/baseData'
export default {
    name: 'settleBillDetail',
    components: {
        DetailList,
        DetailListItem,
        TaskDeliver,
        TaskInteraction
    },
    data () {
        return {
            detail:{settleStatus:''},
            settleStateName:'',
            params:{
                fApi:{},
                rule:PARAMS_SETTLE_USER,
                option:OPTION_INLINE
            },
            table:{
                columns:[],
                loadData:[],
                pagination:{
                    current:1,
                    pageSize: 5,
                    total:0,
                    showSizeChanger: true,
					showQuickJumper: true,
                    pageSizeOptions: ["10", "20", "50", "100"],
                    showTotal: total => `共有 ${total} 条数据`,
                }
            },
        }
    },
    filters: {
        filter_state(value) {
            if(!value)return;
            return SETTLE_BILL_DATA.find(v=>v.value === value).label;
        },
        filterMore (value,num) {
            if (!value) return ''
            if (value.length > num) {
                return value.slice(0,num) + '...'
            }
            return value
        }
    },
    watch:{
      'detail.settleStatus':{
        deep:true,
        handler:function(newV,oldV){
            const flag = newV === 4 ? false:true;
            this.params.fApi.hidden(flag,'settleStatus')
        }
      }
    },
    computed: {
        ...mapGetters(['userInfo'])
    },
    mounted () {
        this.getSettleDateil();
        this.generateRoutes();
        this.initData();
    },
    methods:{
         ...mapActions({
        generateRoutes:'generateRoutes'
        }),
        initData(){
        let sttleUserKey = this.userInfo.roleFiledAuthorities.sttleUserKey;
        if(sttleUserKey && sttleUserKey.length >= 1){
            this.table.columns = COLUMNS_TSTTLE_USER.filter(v=> !sttleUserKey.includes(v.dataIndex));
        }else{
            this.table.columns = COLUMNS_TSTTLE_USER;
        }
        this.getSettleUserList(true);
        },
        async getSettleDateil(){
           const {code,data} = await allGetSettleDetail(this.$route.query.settleBatchCode);
           if(code === '1'){
             Object.assign(this.detail,data);
              this.canteenLineChart();
           }
        },
        canteenLineChart(){
            const pirceMyChart = echarts.init(document.getElementById('projectPirceLine'));
            pirceMyChart.setOption(options,true);
            const numMyChart = echarts.init(document.getElementById('projectNumLine'));
            numMyChart.setOption(options,true);
            let settleErrorNum = 0;
            if(this.detail.settleStatus === 3 || 
            this.detail.settleStatus === 4 || 
            this.detail.settleStatus === 5){
                settleErrorNum = this.detail.settleNum === this.detail.settleSuccessNum ? 0 : this.detail.settleNum - this.detail.settleSuccessNum;
            }
            const priceJson = [
                {"name":"结算总金额","value":this.detail.settleAmount,yAxisIndex:0},
                {"name":"服务费金额","value":this.detail.parkServiceAmount,yAxisIndex:0},
                {"name":"开票总金额","value":this.detail.invoiceAmount,yAxisIndex:0},
                {"name":"结算成功金额","value":this.detail.settleSuccessAmount,yAxisIndex:0},
                {"name":"结算失败金额","value":this.detail.settleFailAmount,yAxisIndex:0},
            ] 
             const numJson = [
                {"name":"结算总笔数","value":this.detail.settleNum,yAxisIndex:1},
                {"name":"结算成功笔数","value":this.detail.settleSuccessNum,yAxisIndex:1},
                {"name":"结算失败笔数","value":settleErrorNum,yAxisIndex:1}
            ] 
            pirceMyChart.setOption({
                xAxis:{
                    data:['结算总金额','服务费金额','开票总金额','结算成功金额','结算失败金额']
                },
                yAxis:{
                    position:'left',
                }
            })
            pirceMyChart.setOption({
                series:[{
                    data:priceJson
                }]
            })
            numMyChart.setOption({
                xAxis:{
                    data:['结算总笔数','结算成功笔数','结算失败笔数']
                },
                yAxis:{
                    position:'right',
                }
            })
            numMyChart.setOption({
                series:[{
                    data:numJson
                }]
            })
            window.onresize = function () {
                pirceMyChart.resize();
                numMyChart.resize()
            }
        },
        async getSettleUserList(flag){
            let params = {};
            if(JSON.stringify(this.params.fApi) !== "{}"){
                const formData = this.params.fApi.formData();
                params.userName = formData.userName;
                params.idCard = formData.idCard;
                params.signStatus = formData.signStatus;
                params.settleStatus = formData.settleStatus;
            }
             if(flag){
                this.table.pagination.current = 1;
                this.table.pagination.pageSize = 10;
            }
            params.settleBatchCode = this.$route.query.settleBatchCode;
            params.pageNum = this.table.pagination.current;
            params.pageSize = this.table.pagination.pageSize;
            const {code,data} = await allSettlementDetail(params);
            if(code === '1'){
                this.table.loadData = data.content;
                this.table.loadData.forEach(v => {
                v.editable = false;
                });
                this.table.pagination.total = data.total || 0;
            }
        },
        handleTableChange(pagination){
            this.table.pagination.current = pagination.current;
            this.table.pagination.pageSize = pagination.pageSize;
            this.getSettleUserList(false);
        },
        editAmount(id){
            const newData = [...this.table.loadData];
            const target = newData.filter(item => id === item.id)[0];
            if (target) {
                target.editable = true;
                this.table.loadData = newData;
            }
        },
        handleChange(value, id, column) {
            const newData = [...this.table.loadData];
            const target = newData.filter(item => id === item.id)[0];
            if (target) {
                target[column] = value;
                this.table.loadData = newData;
            }
        },
        async saveAmount(item){
            if(!item.remark){
                return this.$message.error('交付物必填！');
            }
            const {code} = await allSttleDeliveryEdit(item);
            if(code === '1'){
                this.$message.success('操作成功');
                this.getSettleUserList(false);
            }
        },
        reset(){
            this.params.fApi.resetFields();
            this.getSettleUserList(true);
        },
        close(){
            this.$router.push({name:this.$route.query.flag});
        },
    }
}
</script>
